package com.g17.virtualpetbackend.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

@RestController
public class MediaController {

    private static final Logger LOGGER = LoggerFactory.getLogger(MediaController.class);

    @PostMapping("/multipleImageUpload")
    public List<String> multipleImageUpload(@RequestParam("uploadFiles") MultipartFile[] files, HttpServletRequest request) {
        MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
        LOGGER.info("incoming file number: " + files.length);
        ArrayList<String> serverFileNames = new ArrayList<>();
        for (MultipartFile file : files) {
            String fileType = file.getContentType();
            LOGGER.info("file type: " + fileType);

            if (fileType.contains("image/")) {
                String localPath = "C:/upLoadImg";
                String originalName = file.getOriginalFilename();
                String suffix = originalName.substring(originalName.lastIndexOf("."));
                String newName = UUID.randomUUID() + suffix;
                String url = req.getScheme() + "://" +
                        req.getServerName() + ":"
                        + req.getServerPort()+ "/" + "upLoadImg/"
                        +newName;
                LOGGER.info("uploading: " + originalName);
                if (upload(file, localPath, newName)) {
                    LOGGER.info(originalName + " uploaded to " + url);
                    serverFileNames.add(url);
                } else {
                    LOGGER.error("upload failed");
                }
            } else {
                LOGGER.error("unexpected format");
            }
        }

        return serverFileNames;
    }

    @PostMapping("/VideoUpload")
    public String VideoUpload(@RequestParam("uploadFile") MultipartFile file, HttpServletRequest request) {
        MultipartHttpServletRequest req = (MultipartHttpServletRequest) request;
        String fileType = file.getContentType();
        String url = "";
        LOGGER.info("file type: " + fileType);
        if (fileType.contains("video/")) {
            String localPath = "C:/upLoadVideo";
            String originalName = file.getOriginalFilename();
            String suffix = originalName.substring(originalName.lastIndexOf("."));
            String newName = UUID.randomUUID() + suffix;
            url = req.getScheme() + "://" +
                    req.getServerName() + ":"
                    + req.getServerPort()+ "/" + "upLoadVideo/"
                    +newName;
            LOGGER.info("uploading: " + originalName);
            if (upload(file, localPath, newName)) {
                LOGGER.info(originalName + " uploaded to " + url);
            } else {
                LOGGER.error("upload failed");
            }
        } else {
            LOGGER.error("unexpected format");
        }
        return url;
    }


    private static boolean upload(MultipartFile file, String path, String filename) {
        //create folders if not exist
        File dir = new File(path);
        if (!dir.exists()) {
            if (dir.mkdirs()) {
                LOGGER.info(path + " newly created");
            }
        }

        String realPath = path + "/" + filename;

        File dest = new File(realPath);

        try {
            file.transferTo(dest);
            return true;
        } catch (IOException e) {
            LOGGER.error("transfer failed");
            return false;
        }
    }
}
